import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { ScanRecord, ScanResult, ScanRuleConfig, Product, BatchConfig, BatchInfo } from '../types'
import { useProductStore } from './product'
import dayjs from 'dayjs'

export const useScanStore = defineStore('scan', () => {
  const records = ref<ScanRecord[]>([])
  const scanRule = ref<ScanRuleConfig>({
    pattern: '^BFZFB\\w{4}\\w{4}\\w{1}\\d{4}$', // 默认规则：匹配特定格式的条码
    description: '条码格式：BFZFB + 8位字母数字 + 1位字母 + 4位数字',
    enabled: true
  })
  
  // 添加批次相关配置
  const batchConfig = ref<BatchConfig>({
    batchSize: 12, // 默认批次大小为12
    enabled: true, // 默认启用批次模式
  })
  
  // 当前批次信息
  const currentBatch = ref<BatchInfo | null>(null)
  
  const productStore = useProductStore()

  // 更新扫码规则
  const updateScanRule = (newRule: ScanRuleConfig) => {
    scanRule.value = newRule
  }
  
  // 更新批次配置
  const updateBatchConfig = (newConfig: BatchConfig) => {
    batchConfig.value = newConfig
  }
  
  // 获取当前批次ID (如果没有则创建新批次)
  const getCurrentBatchId = (keyCode: string): string => {
    // 如果批次模式未启用，返回空字符串
    if (!batchConfig.value.enabled) {
      return ''
    }
    
    // 如果当前没有批次或者批次已完成，创建新批次
    if (!currentBatch.value || currentBatch.value.isCompleted) {
      const batchId = `BATCH-${Date.now()}`
      currentBatch.value = {
        batchId,
        currentCount: 0,
        totalCount: batchConfig.value.batchSize,
        keyCode,
        isCompleted: false
      }
      return batchId
    }
    
    // 如果关键代码不匹配，则返回错误
    if (currentBatch.value.keyCode !== keyCode) {
      throw new Error(`当前批次只允许扫描关键代码为 ${currentBatch.value.keyCode} 的产品，您扫描的是 ${keyCode}`)
    }
    
    return currentBatch.value.batchId
  }
  
  // 更新批次信息
  const updateBatchInfo = (keyCode: string): BatchInfo => {
    if (!batchConfig.value.enabled) {
      return {
        batchId: '',
        currentCount: 0,
        totalCount: 0,
        keyCode,
        isCompleted: false
      }
    }
    
    if (!currentBatch.value) {
      // 首次创建批次
      const batchId = getCurrentBatchId(keyCode)
      // 由于getCurrentBatchId会设置currentBatch.value，此时它一定不为null
      if (!currentBatch.value) {
        // 以防万一还是null，创建一个新的批次信息
        return {
          batchId,
          currentCount: 0,
          totalCount: batchConfig.value.batchSize,
          keyCode,
          isCompleted: false
        }
      }
      return currentBatch.value
    }
    
    // 增加当前批次计数
    currentBatch.value.currentCount++
    
    // 检查批次是否完成
    if (currentBatch.value.currentCount >= currentBatch.value.totalCount) {
      currentBatch.value.isCompleted = true
    }
    
    return currentBatch.value
  }
  
  // 开始新批次
  const startNewBatch = () => {
    currentBatch.value = null
  }

  // 检查是否重复扫码
  const isDuplicateScan = (code: string, product: Product) => {
    // 获取今天的开始时间
    const today = dayjs().startOf('day')
    
    // 检查今天的记录中是否有相同的扫码
    return records.value.some(record => {
      const recordDate = dayjs(record.scanTime)
      return recordDate.isAfter(today) && 
             record.scanCode === code
    })
  }

  // 扫描产品
  const scanProduct = (code: string): ScanResult => {
    // 基本格式验证
    if (!code) {
      return {
        success: false,
        message: '无效的扫描码'
      }
    }

    // 使用配置的正则规则验证
    if (scanRule.value.enabled) {
      try {
        const regex = new RegExp(scanRule.value.pattern)
        if (!regex.test(code)) {
          return {
            success: false,
            message: '扫描码格式不符合规则'
          }
        }
      } catch (error) {
        console.error('正则表达式错误:', error)
        return {
          success: false,
          message: '扫码规则配置错误'
        }
      }
    }

    // 查找匹配的产品
    const product = productStore.products.find(p => code.includes(p.keyCode))
    if (!product) {
      return {
        success: false,
        message: '未找到匹配的产品'
      }
    }

    // 检查是否重复扫码
    if (isDuplicateScan(code, product)) {
      return {
        success: false,
        message: '条码重复'
      }
    }
    
    try {
      // 获取批次ID
      const batchId = getCurrentBatchId(product.keyCode)
      
      // 获取当前时间并格式化为ISO字符串
      const now = new Date();
      const scanTime = now.toISOString();
      
      console.log('创建记录，扫描时间:', scanTime);
      
      // 创建扫描记录
      const record: ScanRecord = {
        id: now.getTime(),
        productCode: product.productCode,
        productName: product.productName,
        keyCode: product.keyCode,
        scanCode: code,
        scanTime: scanTime,
        isValid: true,
        batchId: batchConfig.value.enabled ? batchId : undefined
      }
      
      // 添加记录
      records.value.push(record)
      console.log('添加记录成功，当前记录数:', records.value.length);
      
      // 更新批次信息
      const batchInfo = batchConfig.value.enabled 
        ? updateBatchInfo(product.keyCode) 
        : undefined as BatchInfo | undefined
      
      return {
        success: true,
        message: '扫描成功',
        record,
        batchInfo
      }
    } catch (error) {
      if (error instanceof Error) {
        return {
          success: false,
          message: error.message
        }
      }
      return {
        success: false,
        message: '未知错误'
      }
    }
  }

  // 按批次分组获取记录
  const getRecordsByBatch = computed(() => {
    if (!batchConfig.value.enabled) {
      return []
    }
    
    // 获取所有批次ID
    const batchIds = new Set<string>()
    records.value.forEach(record => {
      if (record.batchId) {
        batchIds.add(record.batchId)
      }
    })
    
    // 按批次分组
    return Array.from(batchIds).map(batchId => {
      const batchRecords = records.value.filter(record => record.batchId === batchId)
      const firstRecord = batchRecords[0]
      return {
        batchId,
        keyCode: firstRecord?.keyCode || '',
        productName: firstRecord?.productName || '',
        count: batchRecords.length,
        records: batchRecords,
        startTime: batchRecords.length ? batchRecords[0].scanTime : '',
        endTime: batchRecords.length ? batchRecords[batchRecords.length - 1].scanTime : ''
      }
    }).sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime())
  })

  // 删除记录
  const deleteRecord = (id: number) => {
    const index = records.value.findIndex(r => r.id === id)
    if (index > -1) {
      records.value.splice(index, 1)
    }
  }

  // 批量删除记录
  const deleteRecords = (ids: number[]) => {
    records.value = records.value.filter(r => !ids.includes(r.id))
  }

  // 清空记录
  const clearRecords = () => {
    records.value = []
  }

  return {
    records,
    scanRule,
    batchConfig,
    currentBatch,
    getRecordsByBatch,
    scanProduct,
    deleteRecord,
    deleteRecords,
    clearRecords,
    updateScanRule,
    updateBatchConfig,
    startNewBatch
  }
}, {
  persist: true
}) 